const Coupon = require('../models/Coupon');
const { validationResult } = require('express-validator');
const db = require('../config/database');
const { logger } = require('../utils/logger');

/**
 * 优惠券管理控制器
 */
class CouponController {
  /**
   * 获取所有优惠券（管理员）
   */
  static async getAllCoupons(req, res) {
    try {
      const {
        is_active,
        type,
        page = 1,
        limit = 20,
        sort_by = 'created_at',
        sort_order = 'DESC'
      } = req.query;

      const options = {
        page: parseInt(page),
        limit: parseInt(limit),
        sort_by,
        sort_order
      };

      if (is_active !== undefined) options.is_active = is_active === 'true';
      if (type) options.type = type;

      const coupons = await Coupon.findAll(options);

      res.json({
        success: true,
        data: coupons,
        message: '获取优惠券列表成功'
      });
    } catch (error) {
      logger.error('获取优惠券列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取优惠券列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取可用优惠券（用户）
   */
  static async getAvailableCoupons(req, res) {
    try {
      const userId = req.user.id;
      const coupons = await Coupon.getAvailableCoupons(userId);

      res.json({
        success: true,
        data: coupons,
        message: '获取可用优惠券成功'
      });
    } catch (error) {
      logger.error('获取可用优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '获取可用优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 获取用户优惠券
   */
  static async getUserCoupons(req, res) {
    try {
      const userId = req.user.id;
      const { is_used, page = 1, limit = 20 } = req.query;

      let query = `
        SELECT 
          uc.*,
          c.code,
          c.name,
          c.name_en,
          c.description,
          c.description_en,
          c.type,
          c.value,
          c.min_order_amount,
          c.max_discount_amount,
          c.start_date,
          c.end_date
        FROM user_coupons uc
        JOIN coupons c ON uc.coupon_id = c.id
        WHERE uc.user_id = ?
      `;
      const params = [userId];

      if (is_used !== undefined) {
        query += ' AND uc.is_used = ?';
        params.push(is_used === 'true' ? 1 : 0);
      }

      query += ' ORDER BY uc.created_at DESC';

      // 添加分页
      const offset = (parseInt(page) - 1) * parseInt(limit);
      query += ' LIMIT ? OFFSET ?';
      params.push(parseInt(limit), offset);

      const [rows] = await db.execute(query, params);

      res.json({
        success: true,
        data: rows,
        message: '获取用户优惠券成功'
      });
    } catch (error) {
      logger.error('获取用户优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 获取优惠券详情
   */
  static async getCouponDetail(req, res) {
    try {
      const { id } = req.params;
      const coupon = await Coupon.findById(id);

      if (!coupon) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在'
        });
      }

      res.json({
        success: true,
        data: coupon,
        message: '获取优惠券详情成功'
      });
    } catch (error) {
      logger.error('获取优惠券详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取优惠券详情失败',
        error: error.message
      });
    }
  }

  /**
   * 根据代码获取优惠券
   */
  static async getCouponByCode(req, res) {
    try {
      const { code } = req.params;
      const coupon = await Coupon.findByCode(code);

      if (!coupon) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在'
        });
      }

      res.json({
        success: true,
        data: coupon,
        message: '获取优惠券成功'
      });
    } catch (error) {
      logger.error('根据代码获取优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '获取优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 创建优惠券（管理员）
   */
  static async createCoupon(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const coupon = await Coupon.create(req.body);

      res.status(201).json({
        success: true,
        data: coupon,
        message: '创建优惠券成功'
      });
    } catch (error) {
      logger.error('创建优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '创建优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 更新优惠券（管理员）
   */
  static async updateCoupon(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const { id } = req.params;
      const coupon = await Coupon.update(id, req.body);

      if (!coupon) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在'
        });
      }

      res.json({
        success: true,
        data: coupon,
        message: '更新优惠券成功'
      });
    } catch (error) {
      logger.error('更新优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '更新优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 删除优惠券（管理员）
   */
  static async deleteCoupon(req, res) {
    try {
      const { coupon_id } = req.params;
      const success = await Coupon.delete(id);

      if (!success) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在或删除失败'
        });
      }

      res.json({
        success: true,
        message: '删除优惠券成功'
      });
    } catch (error) {
      logger.error('删除优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '删除优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 验证优惠券
   */
  static async validateCoupon(req, res) {
    try {
      const { code } = req.body;
      const userId = req.user.id;
      const { order_amount, order_items } = req.body;

      if (!code) {
        return res.status(400).json({
          success: false,
          message: '优惠券代码不能为空'
        });
      }

      const validation = await Coupon.validateCoupon(
        code,
        userId,
        order_amount || 0,
        order_items || []
      );

      if (!validation.valid) {
        return res.status(400).json({
          success: false,
          message: validation.message
        });
      }

      // 计算折扣金额
      const discountAmount = await Coupon.calculateDiscount(
        validation.coupon,
        order_amount || 0,
        order_items || []
      );

      res.json({
        success: true,
        data: {
          coupon: validation.coupon,
          discount_amount: discountAmount
        },
        message: '优惠券验证成功'
      });
    } catch (error) {
      logger.error('验证优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '验证优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 领取优惠券
   */
  static async claimCoupon(req, res) {
    try {
      const { coupon_id } = req.body;
      const userId = req.user.id;

      if (!coupon_id) {
        return res.status(400).json({
          success: false,
          message: '优惠券ID不能为空'
        });
      }

      // 检查优惠券是否存在
      const coupon = await Coupon.findById(coupon_id);
      if (!coupon) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在'
        });
      }

      // 验证优惠券是否可领取
      const validation = await Coupon.validateCoupon(coupon.code, userId, 0, []);
      if (!validation.valid) {
        return res.status(400).json({
          success: false,
          message: validation.message
        });
      }

      // 检查用户是否已经领取过
      const [existing] = await db.execute(
        'SELECT id FROM user_coupons WHERE user_id = ? AND coupon_id = ?',
        [userId, coupon_id]
      );

      if (existing.length > 0) {
        return res.status(400).json({
          success: false,
          message: '您已经领取过此优惠券'
        });
      }

      // 领取优惠券
      await db.execute(
        'INSERT INTO user_coupons (user_id, coupon_id) VALUES (?, ?)',
        [userId, coupon_id]
      );

      res.json({
        success: true,
        message: '优惠券领取成功'
      });
    } catch (error) {
      logger.error('领取优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '领取优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 批量发放优惠券（管理员）
   */
  static async batchDistributeCoupons(req, res) {
    try {
      const { coupon_id, user_ids } = req.body;

      if (!coupon_id || !Array.isArray(user_ids) || user_ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '参数错误'
        });
      }

      // 检查优惠券是否存在
      const coupon = await Coupon.findById(coupon_id);
      if (!coupon) {
        return res.status(404).json({
          success: false,
          message: '优惠券不存在'
        });
      }

      const connection = await db.getConnection();
      
      try {
        await connection.beginTransaction();

        // 批量插入用户优惠券
        const values = user_ids.map(userId => [userId, coupon_id]);
        await connection.execute(
          `INSERT IGNORE INTO user_coupons (user_id, coupon_id) VALUES ${values.map(() => '(?, ?)').join(', ')}`,
          values.flat()
        );

        await connection.commit();

        res.json({
          success: true,
          message: `成功发放优惠券给 ${user_ids.length} 个用户`
        });
      } catch (error) {
        await connection.rollback();
        throw error;
      } finally {
        connection.release();
      }
    } catch (error) {
      logger.error('批量发放优惠券失败:', error);
      res.status(500).json({
        success: false,
        message: '批量发放优惠券失败',
        error: error.message
      });
    }
  }

  /**
   * 获取优惠券使用统计（管理员）
   */
  static async getCouponStatistics(req, res) {
    try {
      const { coupon_id, start_date, end_date } = req.query;

      let query = `
        SELECT 
          c.id,
          c.code,
          c.name,
          c.type,
          c.value,
          c.usage_limit,
          c.used_count,
          COUNT(uc.id) as distributed_count,
          COUNT(CASE WHEN uc.is_used = 1 THEN 1 END) as actual_used_count,
          SUM(CASE WHEN uc.is_used = 1 AND o.status = 'completed' THEN o.discount_amount ELSE 0 END) as total_discount_amount
        FROM coupons c
        LEFT JOIN user_coupons uc ON c.id = uc.coupon_id
        LEFT JOIN orders o ON uc.id = o.coupon_id
        WHERE 1=1
      `;
      const params = [];

      if (coupon_id) {
        query += ' AND c.id = ?';
        params.push(coupon_id);
      }

      if (start_date) {
        query += ' AND uc.created_at >= ?';
        params.push(start_date);
      }

      if (end_date) {
        query += ' AND uc.created_at <= ?';
        params.push(end_date);
      }

      query += ' GROUP BY c.id ORDER BY c.created_at DESC';

      const [rows] = await db.execute(query, params);

      res.json({
        success: true,
        data: rows,
        message: '获取优惠券统计成功'
      });
    } catch (error) {
      logger.error('获取优惠券统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取优惠券统计失败',
        error: error.message
      });
    }
  }
}

module.exports = CouponController;